var prmoseHttp = require('../../utils/prmoseHttp.js');
var app = getApp();
var util = require('../../utils/util')
Page({
  data: {
    statusBarHeight: '',
    titleBarHeight: '',
    navHeight: '',
    imgHeight:'',
    titOpra: 0,
    wordTab: true,
    signOpened:false,
    visible:false, //页面是否允许滚动
    tellOpened:false, //
    imgHead:'https://rhi0.xiyun.net/zhuandian/image/',
    feeds:'',
    enable:false,
    title:'活跃金币',
    enveOpened:false, //完成任务奖励弹窗
    countDown:0, //倒计时
    signList:[], //签到日期列表
    userInfo:{},  //用户信息
    accountInfo:{}, //账户信息
    index:-1,
    advList:{}, //云码广告
    isLogin:false,
    coinAmount:0, //金币数
    currency:0,  
    currencyType:1, //金币/红包
    swiper:[],
    redList:[], //红包广告
    isGo:true,
    indexfeeds:2, 
    isSign:false,
    scrollTop:0,
    actOpenone:false,
    actOpentwo:false,
    firstFinishedAwardAmount:0, //首次红包奖励金额
    time:8,
    isGoTb:false,
    isHideGo:false,
    dhAdvInfor:{},
    percent:0,
    bannerInfor:[],
    dhAdvertGuide:false, //第一个引导条开关
    dhAwardDialog:false, //第二个引导条开关
    redPacket:false, //首次红包最外层遮罩
    getPacket:false, //首次红包外层红包
    kaiPacket:true, //打开首次红包
    isTop:true,
    src:'XNTkxNjc4NzA1Ng==',
    shareBox:false,
    imgSrc:'https://rhi0.xiyun.net/zhuandian/',
    imageSrc:'https://ruohuoimage.oss-cn-beijing.aliyuncs.com/zhuandian/image/',
    invitaReward:0,
    userId:'',
    isShow:true,
    people:'',
    setInter:'',
    type:-1,
    isSingle:true,
  },
  options: {
    // 使用基础库内置的数据变化观测器
    observers: true,
  },
  onLoad(options) {
    let that = this;
    //是否是通过邀请过来的
    if(options.userid){
      app.globalData.invitaUserId = options.userid;
      if(my.getStorageSync({key:'userInfo'}).data){
        let id = my.getStorageSync({key:'userInfo'}).data.id;
        that.setData({
          userId:id,
        })
        that.getUserInfo(app.globalData.invitaUserId);
        if(my.getStorageSync({key:'userInfo'}).data.nickname){
          that.setData({
            isShow:true,
          })
        }else{
          that.setData({
            isShow:false,
          })
        }
      }else{
        that.setData({
          isShow:false,
        })
      }
      // my.setStorage({key:'invitaUserId',data:options.userid});
    }else{
      that.getUserInfo();
    }
    my.getSystemInfo({
      success: (res) => {
        that.setData({
          'statusBarHeight': res.statusBarHeight,//状态栏高度 
          'titleBarHeight': res.titleBarHeight,//标题栏高度
          'navHeight': res.statusBarHeight + res.titleBarHeight, //导航栏高度
          'imgHeight': res.windowWidth * 0.86, //背景图片高度
          'toDaytui': res.windowWidth / 698 * 96 + 35,
          'toAdtui': res.windowWidth / 716 * 171,
        })
      }
    });
    that.innerAudioContext = my.createInnerAudioContext(); 
    //来源于优酷的音频码，用于直接播放。支持音频格式：AAC，MP3。如果开发者不传入音频码，控制台不会报错，但无音频播放。
    that.innerAudioContext.src = that.data.src; 
    //是否自动开始播放，默认为 false。
    that.innerAudioContext.autoplay = false;
    //是否循环播放，默认为 false。
    that.innerAudioContext.loop = false;
    //是否遵循系统静音开关，当此参数为 false 时，即使用户打开了静音开关，也能继续发出声音，默认值为 true (注意：此参数仅 iOS 支持)。
    that.innerAudioContext.obeyMuteSwitch = false;
    // that.getUserInfo();
    that.getSwiper();
    const scene = app.globalData.scene;
    if(!scene){
    	if(my.getStorageSync({key:'isCollected'}).data){
      my.alert({
        title:'提示',
        content:'复访路线有误，任务不成功',
        buttonText: '我知道了'
      })
     }
    } else if(scene==1002 || scene == '0000'){
      that.getUserInfo('',scene)
    	// TODO: 任务完成
    }
    my.isCollected({
      success:(res) => {
        // my.showToast({ content: '查询收藏成功',});
      },
      fail:(error)=>{
        my.showToast({content: 'fail'+JSON.stringify(error) });
      },
    });
  },
  onShow(){
    let that = this;
    that.getAccount();
    let date = new Date();
    //每天展示一遍红包轮播弹窗
    if(my.getStorageSync({key:'today'}).data){
      let today = date.getFullYear() +'-'+ date.getMonth() +'-'+ date.getDate();
      let ago = my.getStorageSync({key:'today'}).data;
      if(today != ago){
        that.setData({
          actOpentwo:true
        })
      }else{
        that.setData({
          actOpentwo:false
        })
      }
    }else{
      that.setData({
        actOpentwo:true
      })
    }
    that.setData({
      signOpened:false,
    })
    // let nowTime = date.getFullYear() +'-'+ date.getMonth() +'-'+ date.getDate();
    // if(my.getStorageSync({key:'nowTime'}).data){
    //   let ago = my.getStorageSync({key:'nowTime'}).data;
    //   if(nowTime == ago){
    //     that.setData({
    //       dhAdvertGuide:true,
    //       dhAwardDialog:true,
    //     })
    //   }else{
    //     setTimeout(()=>{
    //       this.dhRef.getTipsStatus();
    //     },1000)
    //   }
    // }else{
    //   setTimeout(()=>{
    //     this.dhRef.getTipsStatus();
    //   },1000)
    // }
    //两个灯火广告组建，轮流展示
    if(my.getStorageSync({key:'dhAdvInfor'}).data){
      if(my.getStorageSync({key:'dhAdvInfor'}).data.isSingle == true ){
        that.setData({
          isSingle:false,
        })
        my.removeStorageSync({key:'dhAdvInfor'})
        my.setStorage({key:'dhAdvInfor',data:{isSingle:false}})
      }else{
        that.setData({
          isSingle:true,
        })
        my.removeStorageSync({key:'dhAdvInfor'})
        my.setStorage({key:'dhAdvInfor',data:{isSingle:true}})
      }
    }else{
      my.setStorage({key:'dhAdvInfor',data:{isSingle:true}})
      that.setData({
        isSingle:true,
      })
    }
  },
  //邀请好友任务完成情况，如完成任务，展示弹窗
  getInvita(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.inviteResult,{},1,'get').then(res=>{
      if(res.code == 200){
        if(res.data == 0){
          that.setData({
            shareBox:false,
          })
        }else{
          that.setData({
            invitaReward:res.data,
            shareBox:true,
          })
        }
        
      }
    })
  },
  //关闭弹窗的邀请好友任务完成弹窗，上报后台，表示用户已查看
  closeInvita(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.confirmInvite,{},1,'POST').then(res=>{
      if(res.code == 200){
        that.setData({
          shareBox:false,
        })
      }
    })
  },
  //账户信息
  getAccount(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.account,{},1,'get').then(res=>{
      if(res.code == 200){
        that.setData({
          accountInfo:res.data
        })
        app.globalData.baseInfo = res.data
        that.getAdv();
        that.enableLing();
        that.signListRef.getSignList();
        that.dhRef.getDhInfo();
        that.dhRef.getBannerInfo();
        that.getInvita();
        that.getStatus();
        if(my.getStorageSync({key:'advInfo'}).data){
          if(my.getStorageSync({key:'advInfo'}).data.source === 2){
            that.checkStatus();
          }else if(my.getStorageSync({key:'advInfo'}).data.source === 4){
            that.checkRuohuo();
          }
        }
      }else if(res.code == 408 || res.code == 405){
        that.GetAuthorize();
      }
    })
  },
  
  //签到
  signOn(){
    let that = this;
    prmoseHttp.encryRequest(prmoseHttp.apiAddress.submitSign,{},1,'post').then(res=>{
      if(res.code == 200){
        // that.getSignList();
        that.getAccount();
        that.setData({
          signOpened:false,
          isSign:false,
        })
      }else{
        my.showToast({
          content:res.message,
        })
      }
    })
  },
  //进页面调用，可能携带邀请人id
  getUserInfo(id,collectCode){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.userInfo,{inviterId:id,collectCode:collectCode},1,'Get').then(res=>{
      if(res.code == 200){
        that.setData({
          userInfo:res.data,
          isLogin:true,
          isShow:true,
        })
        my.setStorage({
          key:'userInfo',
          data:res.data
        })
        that.dhRef.getDh();
        app.globalData.userInfo = res.data
        if(res.data.collectRef){
          if(res.data.collectRef.flag == true){
            that.setData({
              enveOpened:true,
              currency:res.data.collectRef.currency,
              currencyType:res.data.collectRef.currencyType,
            })
          }
        }
      }else{
        that.setData({
          isLogin:false,
        })
      }
    }).catch(err=>{
      console.log(err)
    })
  },
  //授权接口调用之后调用，不携带邀请人ID
  getInfor(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.userInfo,{},1,'Get').then(res=>{
      if(res.code == 200){
        that.setData({
          userInfo:res.data,
          isLogin:true,
          isShow:true,
        })
        my.setStorage({
          key:'userInfo',
          data:res.data
        })
        that.dhRef.getDh();
        app.globalData.userInfo = res.data
      }else{
        that.setData({
          isLogin:false,
        })
      }
    }).catch(err=>{
      console.log(err)
    })
  },
  //登陆授权
  GetAuthorize(){
    my.showLoading({
      title: '登录中'
    });
    var that = this;
    my.getAuthCode({
      scopes: 'auth_base',
      success: function (ress) {
        console.log('authCode:',ress)
        prmoseHttp.publicRequest(prmoseHttp.apiAddress.getToken,{
          appId:app.globalData.appId,
          authCode:ress.authCode,
          thirdPartyType:1,
          inviterId:app.globalData.invitaUserId,
        },1,'get').then(result => {
          if (result.code == 200) {
            app.globalData.token = result.data;
            that.getAdv();
            that.enableLing();
            // that.getInfor();
            that.getUserInfo(app.globalData.invitaUserId,app.globalData.scene)
            that.getSwiper();
            that.dhRef.getDhInfo();
            that.dhRef.getBannerInfo();
            // that.dhRef.getTipsStatus();
          }
        }).catch(err => {
          console.log(err);
        });
      },
      fail: function (ress) {
        my.showToast({
          content: '授权失败',
          type: 'none'
        });
      }
    });
  },
  //是否能领金币
  enableLing(){
    let that = this;
    that.setData({
      title : that.data.title
    })
    // clearInterval(time);
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.enable,{},1,'get').then(res=>{
      if(res.code == 200){
        
        if(res.data.enable == true){
          // title = '活跃金币'
          that.setData({
            enable:res.data.enable,
          })
        }else{
          let previousTime = parseInt(res.data.previousTime/1000);
          let nowTime = Date.parse(new Date(new Date))/1000;
          let overTime = nowTime - previousTime;
          that.countDown(overTime);
        }
      }else if(res.code == 408 || res.code == 405){
        that.GetAuthorize();
      }
    })
  },
  //左上角领金币倒计时
  countDown(overTime){
    let that = this;
      //10分钟领取一次
      clearInterval(that.data.setInter);
      let remainTime = 1800 - overTime;
      let title = '';
      // that.countDown(overTime);
      let min = Math.floor(remainTime/60)
      let second = remainTime%60
      that.data.setInter = setInterval(() => {
        if(overTime < 1800){
          if(second > 1){
            second --
          }else{
            second = 59;
            min--
          }
          title = min+'分'+second+'秒'
          that.setData({
            title:title,
            enable:false,
          })
        }else{
          my.alert({
            title:'销毁'
          })
          title = '领取金币'
          clearInterval(that.data.setInter);
          that.setData({
            title:title,
            enable:true,
          })
        }
      }, 1000);
    },
  // },
  //领金币
  getClaim(){
    let that = this;
    that.setData({
      enable:false
    })
    let enable;
      // if(that.data.enable == true){
      prmoseHttp.encryRequest(prmoseHttp.apiAddress.claim,{},1,'get').then(res=>{
        if(res.code == 200){
          that.getCoinVoice();
          that.setData({
            enveOpened:true,
            currency:res.data,
            currencyType:2,
          })
          that.enableLing();
          that.getAccount();
          enable = true;
        }else if(res.code == 408 || res.code == 405){
          that.GetAuthorize();
          enable = false;
        }else{
          my.showToast({
            content:res.message
          });
          enable = false;
          // that.enableLing();
        }
        that.setData({
          enable:enable
        })
      })
  },
  //信息流广告
  getAdv(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.task,{},1,'get').then(res=>{
      if(res.code == 200){
        that.setData({
          advList:res.data
        })
        let arr = []
        res.data.forEach(obj=>{
          if(obj.currencyType == 1){
            arr.push(obj)
          }
        })
        that.setData({
          redList:arr
        })
      }else if(res.code == 408 || res.code == 405){
        that.GetAuthorize();
      }else{
        my.showToast({
          type:'fail',
          content:res.message
        })
      }
    }).catch(err=>{
      console.log(err);
    })
  },
  //所有广告点击跳转记录状态
  goAdv(e){
    let that = this;
    that.setData({
      actOpentwo:false,
    })
    my.removeStorageSync({key: 'advInfo' });
    my.removeStorageSync({key: 'today' });
    let date = new Date();
    let today = date.getFullYear() +'-'+ date.getMonth() +'-'+ date.getDate();
    my.setStorage({key:'today',data:today})
    let url = e.currentTarget.dataset.url;
    let adId = e.currentTarget.dataset.adId;
    let clickLink = e.currentTarget.dataset.clickLink;
    let tagId = e.currentTarget.dataset.tagId;
    let currency = e.currentTarget.dataset.currency;
    let currencyType = e.currentTarget.dataset.currencyType;
    let source= e.currentTarget.dataset.source;
    let marketingtype = e.currentTarget.dataset.marketingtype;
    let type = e.currentTarget.dataset.type;
    let ext = e.currentTarget.dataset.ext;
    let viewDuration = e.currentTarget.dataset.viewDuration;
    let sign = e.currentTarget.dataset.isSign; //是否是签到
    let invata = e.currentTarget.dataset.invata;
    if(invata == 1){
      that.closeInvita();
    }
    that.setData({
      isSign:sign,
      enveOpened:false,
      isGoTb:false
    })
    my.setStorage({
      key:'advInfo',
      data:{
        url:url,
        adId:adId,
        clickLink:clickLink,
        tagId:tagId,
        currency:currency,
        currencyType:currencyType,
        marketingtype:marketingtype,
        source:source,
        viewDuration:viewDuration,
        ext:ext,
        type:type,
        isSign:sign
      }
    })
    that.goOutSide(source,type,url,ext,adId);
  },
  //云码广告，自营广告点击跳转
  goOutSide(source,type,url,ext,adId){
    let that = this;
    my.setStorage({key:"dhNum",data:3})
    if(source == 2){
      my.ap.navigateToAlipayPage({  
        path:encodeURIComponent(`https://render.alipay.com/p/h5/cloudcode-fe/redirect.html?target=${encodeURIComponent(url)}`)  
      })
    }else if(source == 4){
      that.setData({
        isGo:false,
      })
      if(type == 2 || type == 3){
        my.ap.navigateToAlipayPage({  
        path:ext.parameter,
        success: (res) => {
          // 跳转成功
          that.startWatch(adId);
        },
      })
      }else if(type == 4){
         my.ap.navigateToAlipayPage({  
          path:encodeURIComponent('https://render.alipay.com/p/s/i/?scheme='+encodeURIComponent('alipays://platformapi/startapp?appId=20000067&url='+ext.parameter)),
        })
        that.startWatch(adId);
      }else{
        my.navigateToMiniProgram({
        appId: ext.appid, // 16 位
        path: ext.address,
        success: (res) => {
          that.startWatch(adId);
        },
        fail: (res) => {
          my.alert({
            title: 'navigateToMiniProgram fail',
            content: JSON.stringify(res),
          });
        }
      });
      }
    }else if(source == 1){
      that.goBotttom();
    }else if(source == 5){
      my.setStorage({key:'isCollected',data:true})
      that.collect();
    }
  },
  //收藏
  collect(){
    my.ap.navigateToAlipayPage({
      appCode: 'myAppsGuide',         // 必填 固定值, 进入复访任务流程
      appParams: {
        operationKey: 'revisitGuide', // 必填 复访任务类型, 值可以是: revisitGuide(复访任务) 或 collectRevisitGuide(收藏复访任务)
        operationValue: '2021001114698471',   // 必填 商家的任务小程序app_id
        revisitSource: 'collectRevisitGuide',            // 必填 访问来源 自定义值, 会做透传
      },
      success:(res) => { 						  // 调用成功回调
        
      },
      fail: (res) => { 							  // 调用失败回调
        my.alert({ content: '失败：' + JSON.stringify(res) });
      }
    });
  },
  //自营广告预览开始计时
  startWatch(adId){
    let that = this;
    let time = util.formDate();
    let startTime = Date.parse(new Date())/1000;
    //startTime，开始进行广告时间
    my.setStorage({key:'startTime',data:startTime});
      prmoseHttp.publicRequest(prmoseHttp.apiAddress.startBrowse,{
        advertId:adId,
        clientTime:time,
      },1,'post').then(res=>{
        console.log(res)
      })
  },
  //获取轮播广告
  getSwiper(){
    let that=  this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.getSwiper,{},1,'get').then(res=>{
      that.setData({
        swiper:res.data
      })
    })
  },
  //云码广告检查完成状态
  checkStatus(){
    let that = this;
    let adv = my.getStorageSync({key:'advInfo'}).data;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.checkAdv,{
      adId:adv.adId,
      clickLink:adv.clickLink,
      tagId:adv.tagId,
      marketingType:adv.marketingtype,
    },1,'get').then(res=>{
      if(res.code == 200 && res.data.finished == true){
        if(res.data.ext != null){
          if(res.data.ext.firstFinished == true){
            that.setData({
              redPacket:true,
              firstFinishedAwardAmount:res.data.ext.firstFinishedAwardAmount,
              currency:res.data.currency,
              currencyType:res.data.currencyType,
            })
            if(that.data.isSign == 'true'){
              that.signOn();
            }
          }else{
            my.alert({
              title: '温馨提示',
              content: res.message,
              buttonText: '确定',
              success: () => {
                my.removeStorageSync({key:'advInfo'})
              }
            })
          }
        }else{
          that.getCoinVoice();
          that.setData({
            enveOpened:true,
            currency:res.data.currency,
            currencyType:res.data.currencyType,
          })
        }
        if(that.data.isSign == 'true'){
          that.signOn();
        }
        my.removeStorageSync({key:'advInfo'})
      }else{
        my.alert({
          title: '温馨提示',
          content: '任务未完成或广告已下架',
          buttonText: '确定',
          success: () => {
            my.removeStorageSync({key:'advInfo'})
          }
        })
      }
    })
  },
  //自营广告检查完成状态
  checkRuohuo(){
    let that = this;
    if(!that.data.isGo){
      let time = util.formDate();
      if(my.getStorageSync({key:'startTime'}).data){
        let startTime = my.getStorageSync({key:'startTime'}).data;
        let endTime = Date.parse(new Date())/1000;
        my.removeStorageSync({key:'startTime'})
        let data = my.getStorageSync({key:"advInfo"}).data;
        let overTime = endTime - startTime;
        if( overTime >= data.viewDuration){
          prmoseHttp.publicRequest(prmoseHttp.apiAddress.endBrowse,{
            advertId:data.adId,
            clientTime:time,
            druid:overTime,
          },1,'post').then(res=>{
            if(res.code == 200 && res.data.finished == true){
              if(res.data.ext != null){
                if(res.data.ext.firstFinished == true){
                  that.setData({
                    redPacket:true,
                    firstFinishedAwardAmount:res.data.ext.firstFinishedAwardAmount,
                    currency:res.data.currency,
                    currencyType:res.data.currencyType,
                  })
                  if(that.data.isSign == 'true'){
                    that.signOn();
                  }
                }else{
                  my.alert({
                    title: '温馨提示',
                    content: res.message,
                    buttonText: '确定',
                    success: () => {
                      my.removeStorageSync({key:'advInfo'})
                    }
                  })
                }
              }else{
                that.getCoinVoice();
                that.setData({
                  enveOpened:true,
                  currency:res.data.currency,
                  currencyType:res.data.currencyType,
                })
              }
              if(that.data.isSign == 'true'){
                that.signOn();
              }
              my.removeStorageSync({key:'advInfo'})
            }
          })
        }else{
          that.getAccount();
          my.confirm({
            title: '温馨提示',
            content: '预览'+data.viewDuration+'秒以上才能获得奖励，本次预览时间'+overTime+'秒。\n温馨提示：直播间任务需要安装淘宝APP,否则无法完成，【直播任务多多，建议安装淘宝APP】',
            confirmButtonText: '继续完成任务',
            cancelButtonText: '我知道了',
            success: (result) => {
              if(result.confirm == true){
                that.goOutSide(data.source,data.type,data.url,data.ext,data.adId)
              }
            },
          });
        }
      }
    }
  },
  //关闭每日弹出广告弹窗
  closeTip(){
    my.removeStorageSync({key: 'today' });
    let date = new Date();
    let today = date.getFullYear() +'-'+ date.getMonth() +'-'+ date.getDate();
    my.setStorage({key:'today',data:today})
    this.setData({
      actOpentwo:false,
    })
  },
  //关闭首次红包奖励弹窗
  closeRed(){
    this.setData({
      actOpenone:false,
      enveOpened:true,
    })
  },
  //灯火banner位广告
  goAd(){
    this.setData({
      isGoTb:true,
      type:1,
    })
    let startTime = Date.parse(new Date())/1000;
    my.setStorage({key:"dhBrowseTime",data:startTime})
    my.setStorage({key:"dhNum",data:1})
  },
  //点击灯火广告
  goInfor(){
    this.setData({
      isGoTb:true,
      type:2,
    })
    let startTime = Date.parse(new Date())/1000;
    my.setStorage({key:"dhBrowseTime",data:startTime})
    my.setStorage({key:"dhNum",data:1})
  },
  //获取灯火引导页开关状态
  // getYDYStatus(sta1,sta2){
  //   this.setData({
  //     dhAdvertGuide:sta1,
  //     dhAwardDialog:sta2,
  //   })
  // },
  //获取灯火引导页的开关状态，查询灯火广告完成情况
  // getStatus(){
  //   let that = this;
  //  // 是否展示灯火广告引导页
  //   if(that.data.isHideGo == true && that.data.isGoTb == true && my.getStorageSync({key:'dhNum'}).data == 1 && that.data.dhAdvertGuide == true && that.data.dhAwardDialog == true){
  //     that.endAdv(that.data.type);
  //   }
  // },
  //获取灯火信息流广告信息
  getDhInfo(e){
    if(e){
      this.setData({
        dhAdvInfor:e
      })
    }
  },
  //获取灯火广告banner广告信息
  getBannerInfo(e){
    if(e){
      this.setData({
        bannerInfor:e
      })
    }
  },
  //开始浏览灯火广告
  startAdv(type){
    let that = this;
    let startime = my.getStorageSync({key:'dhBrowseTime'}).data;
    let time = util.transTime(startime*1000);
    let nowTime = Date.parse(new Date())/1000;
    if(nowTime - startime > 1){
      that.setData({
        isGoTb:false,
        isHideGo:false,
      })
    }else{
      prmoseHttp.publicRequest(prmoseHttp.apiAddress.startDh,{
        clientTime:time,
        type:type,
      },1,'post').then(res=>{
        console.log(res)
      })
    }
  },
  //结束浏览灯火广告
  endAdv(type){
    let that = this;
    if(that.data.isHideGo){
      let time = util.formDate();
      if(my.getStorageSync({key:'dhBrowseTime'}).data){
        let startTime = my.getStorageSync({key:'dhBrowseTime'}).data;
        let endTime = Date.parse(new Date())/1000;
        my.removeStorageSync({key:'dhBrowseTime'})
        let overTime = endTime - startTime;
        if( overTime >= that.data.dhAdvInfor.viewDuration){
          prmoseHttp.publicRequest(prmoseHttp.apiAddress.endDh,{
            clientTime:time,
            druid:overTime,
            type:type,
          },1,'post').then(res=>{
            if(res.code == 200 && res.data.finished == true){
              if(res.data.ext != null){
                if(res.data.ext.firstFinished == true){
                  if(that.data.dhAwardDialog == true){
                    that.setData({
                      redPacket:true,
                      firstFinishedAwardAmount:res.data.ext.firstFinishedAwardAmount,
                      currency:res.data.currency,
                      currencyType:res.data.currencyType,
                    })
                  }
                  that.dhRef.getDhInfo();
                  that.dhRef.getBannerInfo();
                  my.removeStorageSync({key:'dhBrowseTime'})
                  if(that.data.isSign == 'true'){
                    that.signOn();
                  }
                }else{
                  if(that.data.dhAwardDialog == true){
                    if(type == 1){
                      viewDuration = that.data.bannerInfor[0].viewDuration;
                    }else{
                      viewDuration = that.data.dhAdvInfor.viewDuration;
                    }
                    my.alert({
                      title: '提示',
                      content: '商品浏览时长不够'+viewDuration+'秒,没有红包哦～',
                      buttonText: '确定',
                      success: () => {
                        
                      }
                    })
                  }
                }
                my.removeStorageSync({key:'dhBrowseTime'})
              }else{
                if(that.data.dhAwardDialog == true){
                  that.getCoinVoice();
                  that.setData({
                    enveOpened:true,
                    currency:res.data.currency,
                    currencyType:res.data.currencyType,
                  })
                }
                that.dhRef.getDhInfo();
                that.dhRef.getBannerInfo();
                my.removeStorageSync({key:'dhBrowseTime'})
                if(that.data.isSign == 'true'){
                  that.signOn();
                }
              }
            }else{
              if(that.data.dhAwardDialog == true){
                my.alert({
                  title: '提示',
                  content: res.message,
                  buttonText: '确定',
                  success: () => {
                    
                  }
                })
              }
            }
          })
        }else{
          that.getAccount();
          let viewDuration = 0;
          if(type == 1){
            viewDuration = that.data.bannerInfor[0].viewDuration;
          }else{
            viewDuration = that.data.dhAdvInfor.viewDuration;
          }
          if(that.data.dhAwardDialog == true){
            my.alert({
              title: '温馨提示',
              content: '商品浏览时长不够'+viewDuration+'秒,没有红包哦～',
              buttonText: '确定',
              success: () => {
                
              }
            })
          }
        }
      }
    }
  },
  goBotttom(){
    let that = this;
    my.createSelectorQuery().select('#top_1').boundingClientRect().exec(res => {
      if(res[0].height){
        my.pageScrollTo({
          scrollTop:res[0].height - 150,
          duration:2
        })
      //  that.dhRef.getTipsShow();
      }
    })
  },
  //日常任务红包音效
  getCoinVoice(){
    this.innerAudioContext.stop()
    this.innerAudioContext.src = 'XNTkwODU5NTc3Mg==';
    this.innerAudioContext.play();
  },
  //首次任务开红包音效
  kaiRed(){
    this.innerAudioContext.stop()
    this.innerAudioContext.src = 'XNTkxNjc4NzA1Ng==';
    this.setData({
      kaiPacket:false,
      getPacket:true,
    })
    this.innerAudioContext.play();
  },
  closeRedPack(){
    this.setData({
      redPacket:false,
      kaiPacket:true,
      getPacket:false,
    })
  },
  close(){
    this.setData({
      isShow:true
    })
  },
  onReady() {
    // 页面加载完成
  },
  onPageScroll: function (e) {
    let that = this;
    var scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度
    if(scrollTop > that.data.scrollTop + 500 && !my.getStorageSync({'key':'scrollTop'}).data){
      // my.alert({
      //   content:'1234'
      // })
      my.setStorage({'key':'scrollTop',data:scrollTop})
    }
    // console.log(scrollTop)
    if (scrollTop <= 5) {
      that.setData({
        titOpra: 0
      });
    } else if (scrollTop <= 100) {
      that.setData({
        titOpra: 1
      });
    } else if (scrollTop <= that.data.imgHeight) {
      that.setData({
        titOpra: 2,
        wordTab: true
      });
    } else {
      that.setData({
        titOpra: 2,
        wordTab: false
      });
    }
    if (scrollTop <= 5) {
      that.setData({
        isTop: true
      });
    }else{
      that.setData({
        isTop: false
      });
    }
  },
  //立即签到按钮
  signOpen(e){
    console.log(e)
    let num = e.currentTarget.dataset.num;
    this.setData({
      signOpened: true,
      visible:true,
      coinAmount:num
    });
  },
  onSignClose(){
    this.setData({
      signOpened: false,
       visible:false
    });
  },
  tellOpened(){
    this.setData({
      tellOpened: true,
      visible:true
    });
  },
  onTellClose(){
    this.setData({
      tellOpened: false,
       visible:false
    });
  },
  onEnveClose(){
    this.setData({
      enveOpened : false
    })
    my.removeStorageSync({
      key: 'advInfo'
    });
  },
  goCoin(){
    my.setStorage({key:"dhNum",data:3})
    my.navigateTo({
      url: '/pages/cashExchange/cashExchange'
    }); 
  },
  goCoins(){
    my.setStorage({key:"dhNum",data:3})
    my.navigateTo({
      url: '/pages/goldCoins/goldCoins'
    }); 
  },
  gored(){
    my.setStorage({key:"dhNum",data:3})
    my.navigateTo({
      url: '/pages/myWallet/myWallet'
    }); 
  },
  goMine(){
    my.switchTab({
      url: '/pages/my/my'
    });
  },
  onRenderSuccess(res){
    console.log(res)
  },
  onRenderFail(res){
    console.log(res)
  },
  onSaveRef(ref) {
    this.feeds = ref;
  },
  redEnvelope(){
    my.setStorage({key:"dhNum",data:3})
      my.navigateTo({
        url: '/pages/redEnvelope/redEnvelope'
      });     
  },
  // 参数 ref 为自定义组件实例的对外引用
  signRef(ref) {
  // 存储自定义组件实例，方便以后调用
    this.signListRef = ref;
  },
  //获取灯火广告实例
  dhAdvRef(ref){
    this.dhRef = ref;
  },
  onHide() {
    let that = this;
    that.setData({
      isHideGo:true,
    })
    if(that.data.isGoTb == true){
      that.startAdv(that.data.type);
    }

    clearInterval(that.data.setInter);
    that.data.setTimer=null;
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // this.getPostion();
    // 页面被下拉
    // 小程序下拉时顺便刷新feeds数据
    this.feeds && this.feeds.refresh && this.feeds.refresh();
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage () {
    return {
      title: '挣点', // 标题
      desc: '任务多多，天天领取现金红包', // 描述
      path: 'pages/index/index?userid='+this.data.userId, // 分享的小程序页面
      success(res){
        my.navigateTo({
          url: '/pages/shareSuccess/shareSuccess'
        }); 
      },
      fail(res){
        console.log('fail',res)
      },
    }
  },
});
